package com.heba.greenmulu.diary;

import android.os.Bundle;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.config.CommonConfig;
import com.heba.bean.diary.ItemTagInfoObject;
import com.heba.event.MessageEvent;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.DensityUtils;
import com.heba.view.FlowLayout;
import com.loopj.android.http.RequestParams;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 添加话题
 * Created by jason on 2020/1/22.
 */
public class ItemDiaryTagAddActivity extends BaseActivity {

    private EditText et_tag;
    private FlowLayout fl_select_tag_view;
    private FlowLayout fl_hot_tag_view;

    /**
     * 熱門標籤
     */
    private List<ItemTagInfoObject> hotTags;

    private List<ItemTagInfoObject> tagInfoObjectList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_tag_add);
        initTopbar();
        findViewById();
        initView();
        getHotTagData();
    }

    @Override
    protected void findViewById() {
        et_tag = findViewById(R.id.et_tag);
        fl_select_tag_view = findViewById(R.id.fl_select_tag_view);
        fl_hot_tag_view = findViewById(R.id.fl_hot_tag_view);
    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.diary_tag_add));
        txt_right.setText(getResources().getString(R.string.diary_tag_add_finish));

        hotTags = new ArrayList<>();

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            tagInfoObjectList = (List<ItemTagInfoObject>) bundle.getSerializable(CommonConfig.TAG_LIST);
        }

        /**
         * 显示选中的标签ui
         */
        if (!tagInfoObjectList.isEmpty()) {
            updateSelectTagFlowView(tagInfoObjectList);
        }

        /**
         * 添加标签
         */
        et_tag.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    if (!et_tag.getText().toString().isEmpty()) {
                        ItemTagInfoObject object = new ItemTagInfoObject();
                        object.setHotTalk(et_tag.getText().toString());
                        tagInfoObjectList.add(object);
                        updateSelectTagFlowView(tagInfoObjectList);
                        et_tag.setText("");
                    }
                }
                return false;
            }
        });

        /**
         * 传递话题标签数据
         */
        txt_right.setOnClickListener(v -> {
            if (!tagInfoObjectList.isEmpty()) {
                MessageEvent event = new MessageEvent();
                event.setEvent(CommonConfig.TAG_LIST);
                event.setTagInfoObjectList(tagInfoObjectList);
                EventBus.getDefault().post(event);
            }
            finishActivity();
        });

    }

    /**
     * 更新热门标签布局
     *
     * @param tags
     */
    private void updateHotFlowView(List<ItemTagInfoObject> tags) {
        fl_hot_tag_view.removeAllViews();

        /**
         * 添加佈局參數
         */
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(this, 30));
        params.rightMargin = DensityUtils.dip2px(this, 10);
        params.bottomMargin = DensityUtils.dip2px(this, 10);
        for (int i = 0; i < tags.size(); i++) {
            fl_hot_tag_view.addView(updateHotFlowRowView(tags.get(i)), params);
        }
    }

    /**
     * 添加item佈局
     */
    private View updateHotFlowRowView(ItemTagInfoObject object) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_search_flow_row, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        tv_text.setText(object.getHotTalk());
        view.setOnClickListener(v -> {
            if (!tagInfoObjectList.contains(object)) {
                tagInfoObjectList.add(object);
                updateSelectTagFlowView(tagInfoObjectList);
            }
        });
        return view;
    }

    /**
     * 更新选中的标签view
     *
     * @param list
     */
    private void updateSelectTagFlowView(List<ItemTagInfoObject> list) {
        fl_select_tag_view.removeAllViews();

        /**
         * 添加佈局參數
         */
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(this, 40));
        params.rightMargin = DensityUtils.dip2px(this, 10);
        params.bottomMargin = DensityUtils.dip2px(this, 5);
        for (int i = 0; i < list.size(); i++) {
            fl_select_tag_view.addView(updateSelectFlowRowView(list.get(i)), params);
        }
    }

    /**
     * @param object
     * @return
     */
    private View updateSelectFlowRowView(ItemTagInfoObject object) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_search_flow_with_delete_row, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        ImageView iv_delete = view.findViewById(R.id.iv_delete);
        tv_text.setText(object.getHotTalk());
        iv_delete.setOnClickListener(v -> {
            tagInfoObjectList.remove(object);
            updateSelectTagFlowView(tagInfoObjectList);
        });
        return view;
    }

    /**
     * 獲取熱門標籤話題
     */
    private void getHotTagData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        client.get(Cfg.BaseUrl + "/Diary/HotTalks", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        hotTags.clear();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemTagInfoObject> tagInfoObjects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemTagInfoObject>>() {
                                }.getType());
                                hotTags.addAll(hotTags.size(), tagInfoObjects);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        /**
                         * 更新熱門話題view
                         */
                        updateHotFlowView(hotTags);
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

}
